package com.bolt.core.view.tag;

import com.bolt.common.utils.StrUtil;
import com.bolt.core.view.components.ComponentsBase;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.StringTokenizer;

public abstract class SelectBaseTag extends InputTag {

    private String itemValue;

    private String list;


    @Override
    protected void populateParams() {
        super.populateParams();
        handleItemValue();
    }


    protected void handleItemValue() {
        if (StrUtil.isNotBlank(itemValue)) {
            String prefix = StrUtil.sub(itemValue, 0, itemValue.indexOf(":"));
            String context = StrUtil.sub(itemValue, itemValue.indexOf(":") + 1,itemValue.length());
            if (StrUtil.equalsIgnoreCase("list", prefix)) {
                component.addParameter("itemValue", doList(context));
            }
            if (StrUtil.equalsIgnoreCase("method", prefix)) {
                doMethod(component, context);
            }
        }
        if (StrUtil.isNotBlank(list)) {
            getRequest().setAttribute("itemValue", getRequest().getAttribute(list));
        }
    }

    private void doMethod(ComponentsBase item, String context) {
        final StringTokenizer parser = new StringTokenizer(context, "|", false);
        while (parser.hasMoreTokens()) {
            String token = StrUtil.trimToEmpty(parser.nextToken());
            String[] keys = token.split("=");
            item.addParameter(keys[0], keys[1]);
        }
    }

    private Map <String, String> doList(String context) {
        Map <String, String> valus = new LinkedHashMap <String, String>();
        final StringTokenizer parser = new StringTokenizer(context, "|", false);
        while (parser.hasMoreTokens()) {
            String token = StrUtil.trimToEmpty(parser.nextToken());
            String[] keys = token.split("=");
            valus.put(keys[0], keys[1]);
        }
        return valus;
    }

    public String getList() {
        return list;
    }

    public void setList(String list) {
        this.list = list;
    }

    public String getItemValue() {
        return itemValue;
    }

    public void setItemValue(String itemValue) {
        this.itemValue = itemValue;
    }

}